/**
 *  zhihu webview
 **/

import React, {Component} from 'react';
import {StyleSheet, WebView} from 'react-native';

export default class DemoZhiHuWebView extends Component {

    constructor(props) {
        super(props);
        this.state = {
            css: "",
            js: "",
            body: ""
        }

    }

    componentDidMount() {
        const {params} = this.props.navigation.state;
        this._asynUrlData(params.id);
    }

    //设置顶部导航栏的内容
    static navigationOptions = ({navigation, screenProps}) => ({
        //左侧标题
        headerTitle: '详情',
        //设置跳转页面左侧返回箭头后面的文字，默认是上一个页面的标题
        headerBackTitle: null,
        //顶部标题栏的样式
        headerStyle: styles.headerStyle,
        //顶部标题栏文字的样式
        headerTitleStyle: styles.headerTitleStyle,
    });

    render() {
        let html =
            "<head>"
            +"<link href=\"" + this.state.css +"\" rel=\"stylesheet\" type=\"text/css \n"
            + "<script language=\"JavaScript\" src=\"" + this.state.js
            +"\"> </script>"
            + "</head>"
            + this.state.body;

        console.log("html:"+html);
        return (
            <WebView
                domStorageEnabled={true}
                javaScriptEnabled={true}
                source={{ html: html }}
            />
        );
    }

    async _asynUrlData(id) {
        let requestUrl = "https://news-at.zhihu.com/api/4/news/" + id;
        let response = await fetch(requestUrl);
        let responseJson = await response.json();
        let css = responseJson.css;
        let js = responseJson.js;
        let body = responseJson.body;
        this.setState({
            css:css,
            js:js,
            body:body,
        });
    }
}

const styles = StyleSheet.create({
    headerStyle: {
        backgroundColor: '#4398ff',
    },
    headerTitleStyle: {
        //标题的文字颜色
        color: 'white',
        //设置标题的大小
        fontSize: 18,
        //居中显示
        alignSelf: 'center',
    },
    itemImage: {
        height: 100,
        width: 100
    },
    itemText: {
        marginLeft: 10,
        fontSize: 16,
        width: 240,
        letterSpacing: 3,
        lineHeight: 28
    }
});

